# -*- coding: utf-8 -*-
# @Author: fanmingxiang@touty.io
# @Date: 2023/3/19 14:55
import threading


class ThreadTimer(threading.Thread):

    def __init__(self, interval, function, args=None, kwargs=None):
        super(ThreadTimer, self).__init__()
        self.function = function
        self.args = args if args is not None else []
        self.kwargs = kwargs if kwargs is not None else {}
        self.interval = interval
        self.finished = threading.Event()

    def run(self):
        self.finished.wait(self.interval)
        if not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
        self.result = self.function(*self.args)
        self.finished.set()

    def cancel(self):
        """Stop the timer if it hasn't finished yet."""
        self.finished.set()

    def get_result(self):
        try:
            return self.result
        except Exception as e:
            return None
